<!--
 * @Description: 流程组件
 * @Author: DHL
 * @Date: 2022-09-14 11:09:34
 * @LastEditors: DHL
 * @LastEditTime: 2022-12-23 15:28:47
-->
<template>
  <div class="flow-wrapper">
    <div class="flow_body" ref="bodyRef" :style="bodyStyle">
      <el-scrollbar height="100%">
        <div class="main">
          <slot></slot>
        </div>

        <div class="approval-record">
          <el-timeline>
            <template v-for="(item, index) in userTaskList">
              <el-timeline-item
                v-if="item.approvalRules.assignedRules.type !== 'initiator'"
                :timestamp="getNodeName(item)"
                placement="top"
                type="primary"
                size="large"
                :icon="UserFilled"
              >
                <el-card shadow="hover">
                  <template v-if="item.assigneeList && item.assigneeList.length > 0">
                    <div
                      v-for="(userItem, userIndex) in item.assigneeList"
                      :key="userItem.id"
                      :class="`user ${userIndex > 0 ? 'mt10' : ''}`"
                    >
                      <div class="txt txt-1">
                        <el-badge value="✔" type="primary">
                          <el-tag size="default">{{ userItem.name }}</el-tag>
                        </el-badge>
                      </div>
                      <div class="txt txt-2">通过 · 2022-09-14 14:10:13</div>
                      <div class="txt txt-3">同意</div>
                    </div>
                  </template>

                  <!-- 发起人自选 -->
                  <template v-if="item.approvalRules.assignedRules.type === 'optional'">
                    <div
                      :class="`${item.assigneeList && item.assigneeList.length > 0 ? 'mt10' : ''}`"
                    >
                      <el-button
                        type="primary"
                        plain
                        size="default"
                        title="选择用户"
                        @click="handleSelectUserOpen(item)"
                      >
                        <SvgIcon iconClass="plus"></SvgIcon>
                      </el-button>
                    </div>
                  </template>
                </el-card>
              </el-timeline-item>
            </template>
          </el-timeline>
        </div>
      </el-scrollbar>
    </div>
    <div class="flow_footer" ref="footerRef">
      <div>
        <el-button @click="handleReset">取 消</el-button>

        <!-- <template v-if="action === 'approval'"> -->
        <el-button>流程图</el-button>
        <el-button type="warning"> 退 回 </el-button>
        <el-button type="info"> 加 签 </el-button>
        <el-button type="success"> 转 审 </el-button>
        <el-button type="danger"> 驳 回 </el-button>
        <el-button type="primary" @click="handleTaskComplete"> 同 意 </el-button>
        <!-- </template> -->

        <!-- <template v-if="['add', 'edit'].includes(action)"> -->
        <el-button type="warning"> 撤 回 </el-button>
        <el-button type="primary" @click="handleSubmit"> 提 交 </el-button>
        <!-- </template> -->

        <slot name="footer"></slot>
      </div>
    </div>

    <selectUser ref="selectUserRef" @submit="handleSubmitSelectUser"></selectUser>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage } from 'element-plus'
  import { cloneDeep } from 'lodash'
  import { apiFlowProcessSearchUserTask, apiFlowTaskComplete } from '/@/api/flow/flowProcess'
  import { FlowUserTaskModel } from '/@/api/flow/model/flowUserTaskModel'
  import selectUser from '/@/pages/components/selectUser.vue'
  import { UserFilled, Promotion } from '@element-plus/icons'

  interface Props {
    /**
     * 流程定义KEY
     */
    procDefKey: string

    /**
     * 业务标识
     */
    businessKey?: string

    /**
     * 流程变量
     */
    values?: any

    /**
     * 操作类型
     * add - 新增
     * edit - 编辑
     * view - 查看
     * approval - 审批
     */
    action: string
  }

  const props = withDefaults(defineProps<Props>(), {
    procDefKey: '',
    businessKey: '',
    values: {},
    action: 'approval'
  })

  const emit = defineEmits(['submit', 'reset'])

  //////////////////////////////////////////////////
  // 属性
  //////////////////////////////////////////////////

  const bodyRef = ref()
  const footerRef = ref()

  /**
   * 用户任务集合
   */
  const userTaskList = ref([] as Array<FlowUserTaskModel>)

  const bodyStyle = reactive({
    height: '100%'
  })

  /**
   * 当前操作的节点
   */
  let activeNode: FlowUserTaskModel = {} as FlowUserTaskModel

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 查询用户任务
   */
  function handleSearchUserTask() {
    apiFlowProcessSearchUserTask({
      procDefKey: props.procDefKey
    }).then((result) => {
      console.info(result)
      if (result?.success) {
        userTaskList.value = result.data
      }
    })
  }

  /**
   * 获取节点审批名称
   * @param node
   */
  function getNodeName(node: FlowUserTaskModel) {
    let rtn = node.name
    let multiWayShow = false

    // 分配人员有多个人
    if (node.assigneeList && node.assigneeList.length > 0) {
      multiWayShow = true
    }

    // 发起人自选 - 自选多个人
    if (
      node.approvalRules.assignedRules.type === 'optional' &&
      node.approvalRules.assignedRules.optionalWay === 'more'
    ) {
      multiWayShow = true
    }

    // 连续多级主管
    if (node.approvalRules.assignedRules.type === 'continuousMultistage') {
      multiWayShow = true
    }

    // 直属主管
    if (node.approvalRules.assignedRules.type === 'supervisor') {
      multiWayShow = true
    }

    if (multiWayShow) {
      const multiInstanceApprovalWay = node.approvalRules.multiInstanceRules.approvalWay
      if ('sequential' === multiInstanceApprovalWay) {
        rtn += '（依次审批）'
      } else if ('parallel' === multiInstanceApprovalWay) {
        rtn += '（会签）'
      } else if ('orSign' === multiInstanceApprovalWay) {
        rtn += '（或签）'
      }
    }
    return rtn
  }

  /**
   * 提交
   */
  function handleSubmit() {
    // 流程启动参数
    const processStartParams = {
      procDefKey: props.procDefKey,
      businessKey: props.businessKey,
      values: props.values,
      userTaskVos: [] as Array<{ id: string; assigneeList: Array<any> }>,
      ccToVos: []
    }

    // 流程审批人
    if (userTaskList.value && userTaskList.value.length > 0) {
      const psUserTaskList: Array<{ id: string; assigneeList: Array<any> }> = []
      userTaskList.value.forEach((item) => {
        psUserTaskList.push({
          id: item.id,
          assigneeList: item.assigneeList
        })
      })
      processStartParams.userTaskVos = psUserTaskList
    }

    emit('submit', processStartParams)
  }

  /**
   * 取消
   */
  function handleReset() {
    emit('reset')
  }

  /**
   * 任务完成
   */
  function handleTaskComplete() {
    apiFlowTaskComplete({
      businessKey: props.businessKey
    }).then((result) => {
      if (result?.success) {
        ElMessage.success(result.message)
      } else {
        ElMessage.warning(result?.message)
      }
    })
  }

  //////////////////////////////////////////////////
  // 生命周期
  //////////////////////////////////////////////////
  onMounted(() => {
    nextTick(() => {
      const footerElement: HTMLDivElement = unref(footerRef)
      const footerHeight = footerElement.offsetHeight
      bodyStyle.height = `calc(100% - ${footerHeight}px)`
    })

    handleSearchUserTask()
  })

  //////////////////////////////////////////////////
  // 暴露出去，父组件才可以调用到
  //////////////////////////////////////////////////
  defineExpose({})

  //////////////////////////////////////////////////
  // 选择用户
  //////////////////////////////////////////////////

  /**
   * 用户选择
   */
  const selectUserRef = ref()

  /**
   * 弹出选择用户
   */
  function handleSelectUserOpen(node: FlowUserTaskModel) {
    activeNode = node
    selectUserRef.value.handleOpen()
  }

  /**
   * 选择用户确认
   * @param userList
   */
  function handleSubmitSelectUser(userList) {
    // 发起人自选 - 自选一个人
    if (
      activeNode.approvalRules.assignedRules.type === 'optional' &&
      activeNode.approvalRules.assignedRules.optionalWay === 'one' &&
      userList &&
      userList.length > 1
    ) {
      ElMessage.warning('只能选择一个用户')
      return
    }

    activeNode.assigneeList = cloneDeep(userList)
  }

  /**
   * 清空选择用户
   */
  function handleClearUser() {}

  /**
   * 删除用户
   * @param user
   */
  function handleDeleteUser(user) {}
</script>

<style scoped lang="scss">
  .flow-wrapper {
    width: 100%;
    height: 100%;
    background-color: #f2f2f2;
    .mt10 {
      margin-top: 10px;
    }

    .flow_body {
      .approval-record {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 10px;
        padding: 20px 0px;
        background-color: #ffffff;

        .el-timeline-item__dot {
          .svg-icon {
            width: 1.3em;
            height: 1.3em;
          }
        }

        .user {
          width: 260px;
          padding: 10px;
          border: 1px dashed #cdd0d6;
          border-radius: 6px;

          .txt {
            padding: 2px 0px;
            color: #909399;
          }
          .txt-1 {
            font-size: 14px;
          }
          .txt-2 {
            text-align: right;
          }

          .txt-3 {
            padding-left: 5px;
          }

          &.succsss {
            color: #409eff;
          }
        }
      }

      .main {
        padding: 10px 20px;
        background-color: #ffffff;
      }
    }

    .flow_footer {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 10px 20px;
      background-color: #ffffff;
    }
  }
</style>
